package com.bdqn.springbootshior.controller;

import com.bdqn.springbootshior.entity.User;
import com.bdqn.springbootshior.service.IUserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class IndexController {
    @Resource
    private IUserService userService;

    @RequestMapping(value = "/index")
    public String index() {
        return "index";
    }

    @RequestMapping(value = "/main")
    public String main() {
        return "main";
    }

    @RequestMapping(value = "/login")
    public String login(String username, String password, Model model, HttpSession session) {
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
            User user = (User) subject.getPrincipal();
            session.setAttribute("loginUser", user);
            return "redirect:/main";
        } catch (UnknownAccountException | IncorrectCredentialsException e) {
            model.addAttribute("msg", "用户名或密码错误，登录失败！");
            return "login";
        } catch (LockedAccountException e) {
            model.addAttribute("msg", "用户禁用，登录失败！");
            return "login";
        } catch (AuthenticationException e) {
            model.addAttribute("msg", "认证异常，登录失败！");
            return "login";
        }
    }

    @RequestMapping(value = "logout")
    public String logout(HttpSession session) {
        session.removeAttribute("loginUser");
        SecurityUtils.getSubject().logout();
        return "redirect:/main";
    }
}
